package com.bjx.flow.mmx.extension.def;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bjx.api.system.domain.vo.UserVO;
import com.bjx.common.core.util.SpringUtil;
import com.bjx.flow.approve.user.ApprovalUserDispose;
import com.bjx.flow.mmx.bean.MmxNodeData;
import com.bjx.flow.mmx.extension.MmxAbstractApprover;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Primary
@Service
public class BjxApprover extends MmxAbstractApprover {
    @Override
    public List<String> customApprover(MmxNodeData nodeData, Map<String, Object> variables) {
        Object obj =  variables.get(nodeData.getProperties().getId());
        if(obj instanceof String){
            String str = (String) obj;
            String[] assignees = str.split(",");
            ArrayList<String> assigneeList = ListUtil.toList(assignees);
            return  assigneeList;
        }
        Map<String, Object> custom = nodeData.getProperties().getCustom();
        JSONObject json = JSONUtil.parseObj(custom);
        json.set("initiatorOrg",variables.get("initiatorOrg"));
        json.set("initiatorCompany",variables.get("initiatorCompany"));
        ApprovalUserDispose approvalUserDispose =  SpringUtil.getBean("relationDisposeHandler");
        List<UserVO> users = new ArrayList<>();
        approvalUserDispose.dispose(json,users);
        return Optional.ofNullable(users.stream().map(UserVO::getUserId).collect(Collectors.toList())).orElse(ListUtil.empty()) ;
    }
}
